package file;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description：实现一个递归遍历文件，并询问删除
 * User：chenshu
 * Date：2023-11-15
 * Time：23:02
 */
public class Demo7 {
    public static void tryDelete(File f, String toDelete) {
        if (f.getName().contains(toDelete)) {
            System.out.println("你要删除的是这个文件吗？(Y/N) -- " + f.getName());
            Scanner scanner = new Scanner(System.in);
            String select = scanner.nextLine();
            if (select.equalsIgnoreCase("Y")) {
                f.delete();
            }
        }
    }
    public static void scanDir(File parentDir, String toDelete) throws IOException {
        System.out.println(parentDir.getCanonicalPath());
        File[] files = parentDir.listFiles();
        //空目录返回
        if (files == null){
            return;
        }
        for (File f : files) {
            //如果是目录，就递归遍历
            if (f.isDirectory()) {
                scanDir(f, toDelete);
            }else  {
                tryDelete(f, toDelete);
            }
        }
    }
    public static void main(String[] args) throws IOException {
        System.out.println("请输入要扫描的路径");
        Scanner scanner = new Scanner(System.in);
        String rootPath = scanner.next();
        File root = new File(rootPath);
        if (!root.exists()) {
            System.out.println("输入的路径不存在");
            return;
        }
        System.out.println("请索引要删除的文件名");
        String toDelete = scanner.next();
        scanDir(root, toDelete);
    }
}
